package com.comba.javafxdemo.controller;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;

import org.controlsfx.dialog.Dialogs;

import com.comba.javafxdemo.MainApp;
import com.comba.javafxdemo.model.Person;
import com.comba.javafxdemo.utils.DateTimeUtils;

import javafx.beans.value.ObservableValue;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.scene.control.TableColumn.CellDataFeatures;
import javafx.util.Callback;

public class PersonOverviewController implements Initializable  {
	@FXML
    private TableView<Person> personTable;
    @FXML
    private TableColumn<Person, String> firstNameColumn;
    @FXML
    private TableColumn<Person, String> lastNameColumn;

    @FXML
    private Label firstNameLabel;
    @FXML
    private Label lastNameLabel;
    @FXML
    private Label streetLabel;
    @FXML
    private Label postalCodeLabel;
    @FXML
    private Label cityLabel;
    @FXML
    private Label birthdayLabel;

    private MainApp mainApp;


    public void setMainApp(MainApp mainApp) {
    	this.mainApp = mainApp;
		this.personTable.setItems(mainApp.getPersonData());
	}

	@Override
	public void initialize(URL location, ResourceBundle resources) {
		this.firstNameColumn.setCellValueFactory(cellData ->
			cellData.getValue().firstNameProperty()
		);

		this.lastNameColumn.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Person,String>, ObservableValue<String>>() {

			@Override
			public ObservableValue<String> call(CellDataFeatures<Person, String> param) {
				return param.getValue().lastNameProperty();
			}
		});

		this.showPersonDetail(null);

		this.personTable.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) ->
			this.showPersonDetail(newValue)
		);

	}


	public void showPersonDetail(Person person) {
		if (person != null) {
	        firstNameLabel.setText(person.getFirstName());
	        lastNameLabel.setText(person.getLastName());
	        streetLabel.setText(person.getStreet());
	        postalCodeLabel.setText(Integer.toString(person.getPostalCode()));
	        cityLabel.setText(person.getCity());
	        String birthday = DateTimeUtils.formatDate(person.getBirthday());
	        birthdayLabel.setText(birthday);
	    } else {
	        // Person is null, remove all the text.
	        firstNameLabel.setText("");
	        lastNameLabel.setText("");
	        streetLabel.setText("");
	        postalCodeLabel.setText("");
	        cityLabel.setText("");
	        birthdayLabel.setText("");
	    }
	}

	@FXML
	private void handleDeletePerson() {
	    int selectedIndex = personTable.getSelectionModel().getSelectedIndex();
	    if(selectedIndex >= 0) {
	    	personTable.getItems().remove(selectedIndex);
	    } else {
	    	Dialogs.create().title("No Selection")
	    	.masthead("No Person Selected")
	    	.message("Please select a person in the table")
	    	.showWarning();
	    }
	}

	public void showPersonEditDialog(Person person, boolean isAdd) {
		try {
			FXMLLoader fxmlLoader = new FXMLLoader(
					PersonOverviewController.class.getResource("/com/comba/javafxdemo/view/PersonEditDialog.fxml"));
			AnchorPane anchorPane = fxmlLoader.load();

			Stage dialogStage = new Stage();
			dialogStage.setTitle("Edit Person");
			dialogStage.initModality(Modality.WINDOW_MODAL);
			dialogStage.initOwner(this.mainApp.getPrimaryStage());
			Scene scene = new Scene(anchorPane);
			dialogStage.setScene(scene);

			PersonEditDialogController controller = fxmlLoader.getController();
			controller.setDialogStage(dialogStage);
			controller.setPerson(person);
			controller.setMainApp(mainApp);
			controller.setAdd(isAdd);

			dialogStage.showAndWait();

		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	@FXML
	private void handleNewPerson() {
	    Person tempPerson = new Person();
	    this.showPersonEditDialog(tempPerson, true);
	}

	@FXML
	private void handleEditPerson() {
	    Person selectedPerson = personTable.getSelectionModel().getSelectedItem();
	    if (selectedPerson != null) {
	        this.showPersonEditDialog(selectedPerson, false);
	        this.showPersonDetail(selectedPerson);

	    } else {
	        // Nothing selected.
	        Dialogs.create()
	            .title("No Selection")
	            .masthead("No Person Selected")
	            .message("Please select a person in the table.")
	            .showWarning();
	    }
	}
}
